<template>
	<view>
		<view class="example">
			<view>
				<textarea v-model="formData.introduction" placeholder="分享我的动态" placeholder-style="font-size: 38rpx;color:grey"></textarea>
			</view>
			<view class="example-body">
				<uni-file-picker limit="4" @select="selectFile" @delete="deleteFile" v-model="imgList"></uni-file-picker>
			</view>
			<view class="btn">
				<button type="primary" class="btn1" @click="addMoment">发布</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData:{
					id:0,
					imgSrc:[],
					introduction:"",
				},
				imgList:[],
				// 虚拟url与真实url的映射数组
				urlMapping:[],
				urlMap:{
					// 虚拟url
					url:"",
					// Oss上存储的路径
					realurl:"",
				}
			}
		},
		onShow() {
			uni.getStorage({
				key:"userId",
				success:res=>{
					this.formData.id=res.data;
				}
			})
		},
		methods: {
			selectFile(e){
				// console.log(e.tempFilePaths[0]);
				// console.log("选择文件");
				uni.uploadFile({
					url:"http://localhost:8080/upload",
					filePath: e.tempFilePaths[0],
					name:"file",
					success:(r=>{
						// 转成json格式
						let result = JSON.parse(r.data);
						//console.log(result);
						this.formData.imgSrc.push(result.data);
						this.urlMap.url=e.tempFilePaths[0];
						this.urlMap.realurl=result.data;
						this.urlMapping.push(this.urlMap);
						//console.log(this.formData.imgSrc);
						uni.showToast({
							title:"上传成功",
							icon:"none",
						});
					})
				});
			},
			deleteFile(e){
				let toDelUrl="";
				// 根绝虚拟url删除真实url
				for (let urlMap of this.urlMapping) {
					if(urlMap.url==e.tempFilePath){
						toDelUrl = urlMap.url;
						this.formData.imgSrc.splice(this.formData.imgSrc.indexOf(toDelUrl),1)
						break;
					}
				}
				//console.log(this.formData.imgSrc);
				uni.showToast({
					title:"删除成功",
					icon:"none",
				});
			},
			addMoment(){
				console.log(this.formData.id);
				uni.request({
					url:"http://localhost:8080/community/add",
					method:"POST",
					header:{
						userId:this.formData.id,
					},
					data:{
						// 用户id
						userId:this.formData.id,
						// 图片集合
						imgs:this.formData.imgSrc,
						// 内容
						content:this.formData.introduction,
					},
					success: (res) => {
						if(res.data.code==200){
							uni.showToast({
								title:"发布成功",
								icon:"none",
							})
						};
						uni.switchTab({
							url:"/pages/moment/moment",
							// 成功跳转失败跳转错误信息
								success(res) {
								console.log('成功啦',res);
								},
								fail(err) {
								console.log('失败啦',err);
								}
						});
					}
				})
			}
		}
	}
</script>

<style>
	page {
		background-color: #111224;
	}
	textarea{
		color: white;
		font-size: 38rpx;
	}
	.btn{
		margin-top: 50rpx;
	}
	.btn1{
		background-color:#3399ff;
	}
</style>
